package graphiterator;

import java.util.Random;

public class Population {

    private Graph[] population;
    private int size;
    private Random r;
    private double maxRank;

    public Population(int maxSize, double maxRank) {
        population = new Graph[maxSize];
        size = 0;
        this.maxRank = maxRank;
        r = new Random(4321);
    }

    public int insert(Graph member) {
        if (member.getRank() > maxRank) {
            return -1;
        }

        int index = size;
        if (index < population.length) {
            // Population is not full, add something
            size++;
            population[index] = member;
        }
        // Population is full, add if greater than last
        else if (member.compareTo(population[index-1]) > 0) {
            // It is greater than last, add it to last
            population[--index] = member;
        }
        else {
            // It is not greater than last
            return -1; // member not added
        }

        // Sort the members
        Graph temp;
        while (index > 0) {
            // Does n need to be swapped with n-1?
            if ( population[index].compareTo(population[index-1]) > 0 ) {
                // Swap
                temp = (Graph) population[index-1];
                population[index-1] = population[index];
                population[index] = temp;
            }
            else {
                // No more swapping needed
                break;
            }

            index--;
        }
        
        return index;
    }

    public int getCurrentSize() {
        return size;
    }

    public Graph[] getPopulation() {
        return population;
    }

    public Graph getFirst() {
        return population[0];
    }

    public Graph getLast() {
        return population[size - 1];
    }

    public Graph getRandom() {
        int index = Math.min(
                r.nextInt(size),
                r.nextInt(size + 1));
        return population[index];
    }
    
}
